import React, { useState, useEffect, useRef, useImperativeHandle } from 'react';
import { connect } from 'dva';
import { Row, Col, Form, Input, Select, Modal, message, Spin, TreeSelect } from 'antd';
import request from '@/utils/request';
import SelectParentBusiObj from './SelectParentBusiObj';

const { TextArea } = Input;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const formItemLayoutText = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

// 判断空对象
const isEmptyObject = obj => {
  if (Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

const namespace = 'busiObjManage';

function BusiObjAdd(props) {
  const { getFieldDecorator } = props.form;
  const addFormEl = useRef();
  const [spinning, setSpinning] = useState(false);
  const [treeSelectData, setTreeSelectData] = useState([]);
  const [applyRuleTypeList, setApplyRuleTypeList] = useState([]);

  useEffect(() => {
    getApplyRuleTypeListSource();
    if (props.busiObjAddType === 'add') {
      if (!isEmptyObject(props.selectBusiObj)) {
        props.form.setFieldsValue({
          parBusiObjName: props.selectBusiObj.busiObjName,
          parBusiObjId: props.selectBusiObj.busiObjId,
          applyRuleObj: null,
        });
      } else {
        props.form.setFieldsValue({
          parBusiObjId: '800100001',
        });
      }
    } else if (props.busiObjAddType === 'modify') {
      request('pmc/pms/busiObj/queryById', {
        method: 'GET',
        data: { busiObjId: props.selectBusiObj.busiObjId },
      }).then(res => {
        if (res && res.success === true) {
          const applyRuleObjTemp = res.data.applyRuleObj !== null ? res.data.applyRuleObj : null;
          props.form.setFieldsValue({
            busiObjId: res.data.busiObjId,
            busiObjName: res.data.busiObjName,
            busiObjNbr: res.data.busiObjNbr,
            busiObjDesc: res.data.busiObjDesc,
            parBusiObjId: res.data.parBusiObjId,
            parBusiObjName: res.data.parBusiObjName,
            className: res.data.className,
            applyRuleObj: applyRuleObjTemp,
          });
        }
      });
    }
    initTreeSelectData();
  }, [props.busiObjAddType]);

  const getApplyRuleTypeListSource = () => {
    const res = [
      {
        name: '条件对象',
        value: 0,
      },
      {
        name: '结果对象',
        value: 1,
      },
      {
        name: '条件结果都适用',
        value: 2,
      },
    ];
    setApplyRuleTypeList(res);
  };

  const initTreeSelectData = () => {
    setTreeSelectData([]);
    setSpinning(true);
    request('pmc/pms/busiObj/queryTreeNode', {
      data: {
        busiObjId: '800100001',
      },
    }).then(res => {
      if (res && res.success === true && res.data) {
        const treeDataList = [];
        treeDataList.push(res.data);
        setTreeSelectData(treeDataList);
        setSpinning(false);
      } else if (res && res.errMessage) {
        message.error(res.errMessage);
      } else {
        message.error('获取父业务对象树失败');
      }
    });
  };

  // 通过dva传递
  const saveSelectParentBusiObjFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectParentBusiObjFlag`,
      payload: params,
    });
  };

  // 新增
  useImperativeHandle(props.cRef, () => ({
    handleAdd: () => {
      return new Promise(function(resolve) {
        props.form.validateFields((err, value) => {
          if (err) return;

          setSpinning(true);

          if (props.busiObjAddType === 'add') {
            request('pmc/pms/busiObj/add', { data: value }).then(res => {
              if (res && res.success === true) {
                setSpinning(false);
                message.success('新增成功');
                resolve(true);
              } else {
                setSpinning(false);
                if (res && res.errMessage) {
                  message.error(res.errMessage);
                } else {
                  message.error('新增失败');
                }
              }
            });
          } else if (props.busiObjAddType === 'modify') {
            request('pmc/pms/busiObj/update', { data: value }).then(res => {
              if (res && res.success === true) {
                setSpinning(false);
                message.success('修改成功');
                resolve(true);
              } else {
                setSpinning(false);
                if (res && res.errMessage) {
                  message.error(res.errMessage);
                } else {
                  message.error('修改失败');
                }
              }
            });
          }
        });
      });
    },
  }));

  const handleOk = () => {
    addFormEl.current.handleSelectParentObj().then(res => {
      saveSelectParentBusiObjFlag(false);
      if (!isEmptyObject(res)) {
        props.form.setFieldsValue({
          parBusiObjId: res.busiObjId,
          parBusiObjName: res.busiObjName,
        });
      }
    });
  };

  const handleCancel = () => {
    saveSelectParentBusiObjFlag(false);
  };

  return (
    <Spin spinning={spinning}>
      <Form>
        <Row>
          <Col span={12}>
            <Form.Item label="业务对象名称" {...formItemLayout}>
              {getFieldDecorator('busiObjName', {
                rules: [
                  {
                    required: true,
                    message: '业务对象名称不能为空',
                  },
                ],
              })(
                <Input
                  placeholder="请输入业务对象名称"
                  disabled={!(props.busiObjAddType === 'add' || props.busiObjAddType === 'modify')}
                  maxLength={20}
                />
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="业务对象编码" {...formItemLayout}>
              {getFieldDecorator('busiObjNbr', {
                rules: [
                  {
                    required: true,
                    message: '业务对象名称不能为空',
                  },
                ],
              })(
                <Input
                  placeholder="请输入业务对象名称"
                  disabled={!(props.busiObjAddType === 'add' || props.busiObjAddType === 'modify')}
                  maxLength={30}
                />
              )}
            </Form.Item>
          </Col>
        </Row>
        {/* <Row>
          <Col span={12}>
            <Form.Item label="父业务对象" {...formItemLayout}>
              {getFieldDecorator('parBusiObjId')(
                <Input.Search
                  disabled={props.busiObjAddType === 'add' || props.busiObjAddType === 'modify' ? false : true}
                  readOnly
                  placeholder="请选择父业务对象"
                  onSearch={handleSelectParentObj}
                  allowClear={true}
                />
              )}
            </Form.Item>
          </Col>
        </Row> */}
        <Row>
          <Col span={12}>
            <Form.Item label="父业务对象" {...formItemLayout}>
              {getFieldDecorator('parBusiObjId')(
                <TreeSelect
                  treeNodeLabelProp="busiObjName"
                  treeNodeFilterProp="busiObjId"
                  style={{ width: '100%' }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  treeData={treeSelectData}
                  placeholder="请选择父业务对象"
                  treeDefaultExpandAll
                  // treeIcon={true}
                  // expandIcon={(props) => customExpandIcon(props)}
                  // onChange={onChange}
                  // onSelect={handleTreeNodeSelect}
                />
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="适用规则对象类型" {...formItemLayout}>
              {getFieldDecorator('applyRuleObj')(
                <Select style={{ width: '100%' }} showSearch allowClear>
                  {applyRuleTypeList.length
                    ? applyRuleTypeList.map(item => {
                        return (
                          <Select.Option value={item.value} key={item.value}>
                            {item.name}
                          </Select.Option>
                        );
                      })
                    : null}
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Form.Item label="业务对象类路径" {...formItemLayoutText}>
              {getFieldDecorator('className')(
                <Input
                  placeholder="请输入业务对象类路径"
                  disabled={!(props.busiObjAddType === 'add' || props.busiObjAddType === 'modify')}
                  maxLength={200}
                />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Form.Item label="业务对象描述" {...formItemLayoutText}>
              {getFieldDecorator('busiObjDesc')(
                <TextArea
                  rows={5}
                  placeholder="请输入业务对象描述"
                  disabled={!(props.busiObjAddType === 'add' || props.busiObjAddType === 'modify')}
                  maxLength={500}
                />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row style={{ display: 'none' }}>
          <Col span={1}>
            <Form.Item label="业务对象Id" {...formItemLayout}>
              {getFieldDecorator('busiObjId')(<Input disabled />)}
            </Form.Item>
          </Col>
        </Row>
      </Form>
      {/* 选择父业务对象 */}
      <Modal
        title="选择父业务对象"
        visible={props.selectParentBusiObjFlag}
        onOk={handleOk}
        onCancel={handleCancel}
        width="50%"
        destroyOnClose
      >
        <SelectParentBusiObj cRef={addFormEl} />
      </Modal>
    </Spin>
  );
}

export default connect(({ busiObjManage }) => ({
  selectBusiObj: busiObjManage.selectBusiObj,
  busiObjAddType: busiObjManage.busiObjAddType,
  selectParentBusiObjFlag: busiObjManage.selectParentBusiObjFlag,
}))(Form.create()(BusiObjAdd));
